/*
 * @Author: leechoy 1419352779@qq.com
 * @Date: 2025-01-14 11:32:43
 * @LastEditors: leechoy 1419352779@qq.com
 * @LastEditTime: 2025-01-14 11:33:12
 * @FilePath: /miniClient/pages/template/list.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
Page({
  data: {
    searchValue: '',
    templates: [],
    isSelectMode: false
  },

  onLoad(options) {
    this.setData({
      isSelectMode: options.select === 'true'
    })
    this.getTemplates()
  },

  // 搜索
  onSearch(e) {
    this.setData({
      searchValue: e.detail
    })
    this.getTemplates()
  },

  // 获取模板列表
  async getTemplates() {
    wx.showLoading({ title: '加载中' })
    try {
      const res = await wx.request({
        url: 'your-api-url/template/list',
        data: {
          keyword: this.data.searchValue
        }
      })

      this.setData({
        templates: res.data.list
      })
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 选择模板
  selectTemplate(e) {
    const template = e.currentTarget.dataset.template
    if (this.data.isSelectMode) {
      // 选择模式下，返回上一页并传递数据
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      prevPage.setData({
        templateId: template.id,
        templateName: template.title
      })
      wx.navigateBack()
    } else {
      // 查看模式下，跳转到模板详情
      wx.navigateTo({
        url: `/pages/template/detail?id=${template.id}`
      })
    }
  }
}) 